#!/bin/bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2022-09-17 00:44:57
# @LastEditTime: 2023-11-08 02:23:35
# @Description:
###
set -e
set -o pipefail

HOSTNAME=$2
ZBX_SERVER=$1
WEB_PORT=8080
ZABBIX_AGENT_RPM="/root/zabbix-agent2-6.0.7-1.el7.x86_64.rpm"

# 检查必要的工具是否存在
for cmd in yum netstat curl tar; do
    if ! command -v $cmd &>/dev/null; then
        echo "Error: $cmd is not installed."
        exit 1
    fi
done

# 安装 Zabbix agent
if [ -f $ZABBIX_AGENT_RPM ]; then
    yum install -y $ZABBIX_AGENT_RPM
else
    yum --debuglevel=1 install http://$ZBX_SERVER$WEB_PORT/agent/zabbix-agent2-6.0.7-1.el7.x86_64.rpm -y
fi

# 添加授权
which netstat | xargs chmod u+s # 端口发现需要netstat权限
(grep "zabbix" -lr /etc/sudoers) || cat >>/etc/sudoers <<EOF
Defaults:zabbix !requiretty # 不需要提示终端登录
zabbix ALL=(ALL)    NOPASSWD: /bin/netstat
EOF

# 修改主机名
Set_hostname() {
    if [ -f /etc/hostname ]; then
        echo "$HOSTNAME" >/etc/hostname
    fi
    sed -i "/HOSTNAME/c HOSTNAME=$HOSTNAME" /etc/sysconfig/network || echo "HOSTNAME=$HOSTNAME" >>/etc/sysconfig/network
    hostname $HOSTNAME
    grep $HOSTNAME /etc/hosts || echo "127.0.0.1 $HOSTNAME" >>/etc/hosts
}

# 修改Zabbix agent配置
Set_zabbix_conf() {
    cat >/etc/zabbix/zabbix_agent2.conf <<EOF
PidFile=/run/zabbix/zabbix_agent2.pid
LogFile=/var/log/zabbix/zabbix_agent2.log
LogFileSize=0
Server=${ZBX_SERVER}
ServerActive=${ZBX_SERVER}
Hostname=$HOSTNAME
Include=/etc/zabbix/zabbix_agent2.d/*.conf
Include=./zabbix_agent2.d/plugins.d/*.conf
ControlSocket=/tmp/agent.sock
EOF
    curl -fsSL -O --max-time 30 --retry 3 --retry-delay 6 http://$ZBX_SERVER$WEB_PORT/agent/zabbix_agentd.d.tar.gz
    # tar指定解压路径,去掉一层目录
    tar zxvf zabbix_agentd.d.tar.gz -C /etc/zabbix/zabbix_agent2.d/ --strip-components 1
    systemctl restart zabbix-agent2
}

# Set_hostname
Set_zabbix_conf
